package com.woniuxy.automotivemanagementsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.automotivemanagementsystem.entity.Role;
import com.woniuxy.automotivemanagementsystem.entity.User;
import com.woniuxy.automotivemanagementsystem.entity.vo.UserVo;
import com.woniuxy.automotivemanagementsystem.mapper.RoleMapper;
import com.woniuxy.automotivemanagementsystem.mapper.UserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.automotivemanagementsystem.service.RoleService;
import com.woniuxy.automotivemanagementsystem.service.UserService;
import com.woniuxy.automotivemanagementsystem.utils.PageResult;
import com.woniuxy.automotivemanagementsystem.utils.Result;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

import static cn.hutool.core.date.DateTime.now;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public User login(String username, String password) {
        String md5 = DigestUtils.md5Hex(password);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(username!=null && !username.trim().isEmpty(),User::getUsername,username)
                    .eq(password!=null && !password.trim().isEmpty(),User::getPassword,md5);
        queryWrapper.eq(User::getStatus,0);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public Result register(String username, String password) {
        if(username == null || username.trim().isEmpty() || password == null || password.trim().isEmpty()){
            return Result.error("用户名或密码不能为空").code(528);
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);
        if(userMapper.selectOne(queryWrapper) != null){
            return Result.error("用户已存在").code(529);
        }else{
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setStatus(0);
            user.setType("普通用户");
            user.setCreatetime(now());
            user.setImgPath("https://org-yixue-ykj-bucket.oss-cn-nanjing.aliyuncs.com/avatar/cxy.jpg");
            userMapper.insert(user);

            roleMapper.insertUserRole(user.getUid(),3);
            return Result.success("注册成功");
        }
    }
    /*
    * 条件查询所有
    * */
    @Override
    public Result queryCondition(UserVo vo) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(vo.getUsername()!=null && !vo.getUsername().trim().isEmpty(),User::getUsername,vo.getUsername())
                .eq(vo.getType()!=null && !vo.getType().trim().isEmpty(),User::getType,vo.getType())
                .eq(vo.getStatus()!=null,User::getStatus,vo.getStatus())
                .le(vo.getCreatetime()!=null,User::getCreatetime,vo.getCreatetime());
        //2.分页查询
        Page<User> page = this.page(new Page<>(vo.getPageNum(),vo.getPageSize()), queryWrapper);
        //3.获取当前页的用户数据
        List<User> list = page.getRecords();
        //遍历集合
        for(User u : list){
            //根据当前用户编号查询关联角色信息
            List<Role> roleList = roleService.findRoleByUserId(u.getUid());
            //把角色集合设置到当前用户下
            u.setRoles(roleList);
        }
        //3.封装响应数据
        PageResult<User> pageResult = new PageResult<>(page.getCurrent(), page.getSize(), page.getTotal(), list);
        return Result.success(pageResult); //res.data.data.list
    }
    /*
    * 分配角色
    * */
    @Override
    @Transactional
    public void updateUserRole(Integer[] rIds, User user) {
        //删除用户角色关系
        userMapper.deleteUserRole(user.getUid());
        //角色优先级逻辑
        boolean isAdmin = Arrays.asList(rIds).contains(1);
        boolean isSvip = Arrays.asList(rIds).contains(2);
        if (isAdmin) {
            user.setType("管理员");
        } else if (isSvip) {
            user.setType("svip");
        } else {
            user.setType("普通用户");
        }
        //批量插入
        for(Integer rId : rIds){
            userMapper.insertUserRole(user.getUid(),rId);
        }
        //修改用户信息
        userMapper.updateById(user);
    }
}
